package com.pactera.madp.cp.controller.oms.department;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.admin.api.dto.WxDeptDto;
import com.pactera.madp.cp.api.vo.dept.DeptEmployeeLinkVO;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.security.annotation.Inner;
import com.pactera.madp.cp.api.dto.dept.ReqDeptPageDTO;
import com.pactera.madp.cp.api.entity.WorkDeptEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeDepartmentEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.vo.DeptEmployeeVo;
import com.pactera.madp.cp.api.vo.dept.DeptVo;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.service.IWorkDeptService;
import com.pactera.madp.cp.service.IWorkEmployeeDepartmentService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import com.pactera.madp.cp.service.impl.AccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhaojinjian
 * @ClassName DepartmentController.java
 * @Description TODO
 * @createTime 2021/1/7 11:41
 */
@RestController
@AllArgsConstructor
@RequestMapping("/workdepartment")
@Api(value = "workdepartment", tags = "部门管理")
public class DepartmentController {

    private IWorkDeptService deptService;
    private IWorkEmployeeService workEmployeeService;
    private IWorkEmployeeDepartmentService workEmployeeDepartmentService;
    private IWorkDeptService workDeptService;

    /**
     * @description 部门管理 - 部门列表
     * @author zhaojinjian
     * @createTime 2021/1/7 13:38
     */
    @GetMapping("/index")
    @ApiOperation(value = "查询部门列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="searchKeyWords",value="搜索关键字",dataType="String")
    })
    public R getDeptList(String searchKeyWords) {
        Integer corpId = CorpContextHolder.getCorpId();
        if (corpId == null) {
            throw new CheckedException("未选择登录企业，不可操作");
        }
        return R.ok(deptService.getWorkDepartments(searchKeyWords, corpId));
    }

    @GetMapping("/index-new")
    @ApiOperation(value = "查询部门列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="searchKeyWords",value="搜索关键字",dataType="String")
    })
    public R getDeptList1(String searchKeyWords) {
        Integer corpId = CorpContextHolder.getCorpId();
        if (corpId == null) {
            throw new CheckedException("未选择登录企业，不可操作");
        }
        return R.ok(deptService.getWorkDepartments1(searchKeyWords, corpId));
    }

    /**
     * @description 部门管理 - 部门列表
     * @author zhaojinjian
     * @createTime 2021/1/7 13:38
     */
    @GetMapping("/getAllDept")
    @ApiOperation(value = "查询部门列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="searchKeyWords",value="搜索关键字",dataType="String")
    })
    public void getAllDept(String searchKeyWords, HttpServletResponse response, OutputStream out) {
        Integer corpId = CorpContextHolder.getCorpId();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("name","姓名");
        writer.addHeaderAlias("wxUserId","企业微信id");
        List<WorkDeptEntity> depts = deptService.list(Wrappers.<WorkDeptEntity>query().eq("corp_id", corpId));
        ArrayList<DeptVo> vos = new ArrayList<>();
        depts.forEach(f -> {
            DeptVo vo = new DeptVo();
            vo.setName(f.getName());
            vo.setId(f.getWxDepartmentId());
            vos.add(vo);
        });
        if (vos.isEmpty()) vos.add(new DeptVo());

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=excel-error.xlsx");
        writer.write(vos, true);
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    /**
     * @description 部门管理 - 部门下的成员列表
     * @author zhaojinjian
     * @createTime 2021/1/7 13:37
     */
    @GetMapping("/workemployeedepartment/memberindex")
    @ApiOperation(value = "部门下的成员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="departmentIds",value="部门id",dataType="String")
    })
    public R getDeptMemberList(String departmentIds) {
        Integer corpId = CorpContextHolder.getCorpId();
        if (corpId == null) {
            throw new CheckedException("未选择登录企业，不可操作");
        }
        String[] deptIds = departmentIds.split(",");
        List<Integer> deptIdList = new ArrayList<>();
        for (int i = 0; i < deptIds.length; i++) {
            deptIdList.add(Integer.parseInt(deptIds[i]));
        }
        return R.ok(deptService.getDeptMemberList(deptIdList, corpId));
    }

    @GetMapping("/getDeptMemberByAdmin")
    @ApiOperation(value = "当前用户部门下的成员列表")
    public R getDeptMemberByAdmin() {
        List<Integer> employeeIds = workEmployeeDepartmentService.getDeptEmpIdListByAdmin();
        List<WorkEmployeeEntity> list = workEmployeeService.lambdaQuery().in(WorkEmployeeEntity::getId, employeeIds).eq(WorkEmployeeEntity::getStatus, 1).list();
        ArrayList<DeptEmployeeVo> vos = new ArrayList<>();
        list.forEach(f -> {
            DeptEmployeeVo deptEmployeeVo = new DeptEmployeeVo();
            BeanUtils.copyProperties(f, deptEmployeeVo);
            vos.add(deptEmployeeVo);
        });
        return R.ok(vos);
    }

    /**
     *
     * @description:部门管理 - 根据手机号匹配成员部门下拉列表
     * @author: Huayu
     * @time: 2021/2/7 15:56
     */
    @GetMapping("/selectbyphone")
    @ApiOperation(value = "根据手机号匹配成员部门下拉列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="phone",value="搜索手机号",dataType="String")
    })
    public R selectDeptListByPhone(String phone) {
        if(StringUtil.isEmpty(phone)){
            throw new CheckedException("手机号不能为空");
        }
        //根据手机号查询成员通讯录
        String clStr = "id,corp_id";
        List<WorkEmployeeEntity> workEmployeeEntityList = workEmployeeService.getWorkEmployeesByMobile(phone,clStr);
        if(workEmployeeEntityList == null || workEmployeeEntityList.size() == 0){
            return R.ok();
        }
        List<String> employeeIdList = new ArrayList<String>();
        for (WorkEmployeeEntity workEmployeeEntity:
        workEmployeeEntityList) {
            if(workEmployeeEntity.getCorpId().equals(AccountService.getCorpId())){
                employeeIdList.add(workEmployeeEntity.getId().toString());
            }
        }
        if(employeeIdList == null || employeeIdList.size() == 0){
            return R.ok();
        }
        //查询成员-部门关联表
        clStr = "id,department_id";
        List<WorkEmployeeDepartmentEntity> workEmployeeDepartmentEntityList = workEmployeeDepartmentService.getWorkEmployeeDepartmentsByEmployeeIds(employeeIdList,clStr);
        if(workEmployeeDepartmentEntityList == null || workEmployeeDepartmentEntityList.size() == 0){
            return R.ok();
        }
        StringBuilder sb = new StringBuilder();
        String departmentId = null;
        //查询部门信息
        for (WorkEmployeeDepartmentEntity workEmployeeDepartmentEntity:
        workEmployeeDepartmentEntityList) {
            departmentId = workEmployeeDepartmentEntity.getDepartmentId().toString();
            sb = sb.append(departmentId).append(",");
        }
        String ids = sb.substring(0,sb.length()-1);
        //查询部门信息
        clStr = "id,corp_id,name";
        List<WorkDeptEntity> workDeptEntityList = workDeptService.getWorkDepartmentsById(ids,clStr);
        if(workDeptEntityList == null || workDeptEntityList.size() == 0){
            return R.ok();
        }
        List<Map<String,Object>> mapList = new ArrayList();
        Map<String,Object>  mapData = null;
        for (WorkDeptEntity workDeptEntity:
        workDeptEntityList) {
            mapData = new HashMap<String,Object>();
            mapData.put("corpId",workDeptEntity.getCorpId());
            mapData.put("workDepartmentId",workDeptEntity.getId());
            mapData.put("workDepartmentName",workDeptEntity.getName());
            mapList.add(mapData);
        }
        return R.ok(mapList);
    }

    /**
     *
     * @description:组织管理- 查看人员列表
     * @author: Huayu
     * @time: 2021/2/9 14:14
     */
    @GetMapping("/showemployee")
    @ApiOperation(value = "查看人员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="departmentId",value="部门id",dataType="String")
    })
    public R showEmployee(String employeeId, String employeeName, String departmentId, Page page) {
//        page.setSize(9999L);
        return workEmployeeDepartmentService.handleShowEmpData(departmentId, page, employeeId, employeeName);
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public R pageIndex(ReqDeptPageDTO req, Page page) {
        return workEmployeeDepartmentService.handlePageIndexData(req, page);
    }

    //-------------------------upms工程更新部门同步企业微信远程调用接口-----------------------------

    /**
     * 创建部门
     * @return
     */
//    @SysLog("创建部门")
    @Inner
    @PostMapping
    @ApiOperation(value = "创建部门")
    public R<Integer> createDept(@RequestBody WxDeptDto dto) {

        return deptService.createDept(dto);
    }

    /**
     * 更新部门
     * @return
     */
//    @SysLog("更新部门")
    @Inner
    @PutMapping
    @ApiOperation(value = "更新部门")
    public R<Boolean> updateDept(@RequestBody WxDeptDto dto) {
        return deptService.updateDept(dto);
    }

    /**
     * 删除部门
     * @return
     */
//    @SysLog("删除部门")
    @Inner
    @DeleteMapping("/{wxDeptId}")
    @ApiOperation(value = "删除部门")
    R<Boolean> deleteDept(@PathVariable("wxDeptId") Integer wxDeptId) {
        return deptService.deleteDept(wxDeptId);
    }

    @GetMapping("/link-objects/{deptId}")
    @ApiOperation(value = "根据登录机构id获取联动对象列表")
    public R<DeptEmployeeLinkVO> getLinkObjects(@PathVariable Integer deptId) {
        return R.ok(deptService.getLinkObjects(deptId));
    }

}
